package com.sutong.client.config;

import com.sutong.client.interceptor.SignHttpRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * RestTemplateConfig 配置请求拦截器
 *
 * @author sutong
 * @date 2024-07-15 9:54
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        BufferingClientHttpRequestFactory simpleBufferingClientHttpRequest = new BufferingClientHttpRequestFactory(requestFactory);
        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(3500);
        RestTemplate restTemplate = new RestTemplate(simpleBufferingClientHttpRequest);
        restTemplate.getInterceptors().add(restTemplateInterceptor());
        // 防止响应中文乱码
        restTemplate.getMessageConverters().stream().filter(StringHttpMessageConverter.class::isInstance).map(StringHttpMessageConverter.class::cast).forEach(a -> {
            a.setWriteAcceptCharset(false);
            a.setDefaultCharset(StandardCharsets.UTF_8);
        });
        return restTemplate;
    }


    @Bean
    public ClientHttpRequestInterceptor restTemplateInterceptor() {
        return new SignHttpRequestInterceptor();
    }

}
